package com.atguigu.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.constant.RedisConst;
import com.atguigu.entity.UserInfo;
import com.atguigu.result.RetVal;
import com.atguigu.service.UserInfoService;
import com.atguigu.util.IpUtil;
import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserInfoService userInfoService;
    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/login")
    public RetVal login(@RequestBody UserInfo userInfo, HttpServletRequest request){
        //根据用户输入的账号密码查询数据库用户信息
        UserInfo dbUser=userInfoService.queryUserFromDb(userInfo);
        if(dbUser!=null){
            //1.返回给页面信息的map
            Map<String, Object> retMap = new HashMap<>();
            //2生成一个token用户信息返回给页面cookie
            String token = UUID.randomUUID().toString();
            retMap.put("token",token);
            //3.把用户昵称信息也放入
            retMap.put("nickName",dbUser.getNickName());
            //4.将用户信息存储redis
            //构造用户信息的key 一个前缀+token
            //存储的信息，用户id 用户IP地址
            String userKey = RedisConst.USER_LOGIN_KEY_PREFIX+ token;
            JSONObject loginInfo  = new JSONObject();
            loginInfo.put("userId",dbUser.getId().toString());
            loginInfo.put("loginIp", IpUtil.getIpAddress(request));//ip地址

            redisTemplate.opsForValue().set(userKey,loginInfo.toJSONString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return RetVal.ok(retMap);
        }else {
            return RetVal.fail().message("登录失败！");
        }
    }


    //退出
    @GetMapping("logout")
    public RetVal logout(HttpServletRequest request){
        String userKey=RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token");
        redisTemplate.delete(userKey);
        return RetVal.ok();
    }

}
